#include <string.h>
#include "7za.h"
#include "com_snda_Andro7z_Andro7za.h"
#include "7za_log.h"

#define  ARGC 4
static const char *test_args[ARGC + 1] =
		{ "7za", "x", "-o/mnt/sdcard/extractarchiveandroid",
				"/mnt/sdcard/7za123456789.7z", 0 };

extern "C" JNIEXPORT jint JNICALL Java_com_snda_Andro7z_Andro7za_a7za_1print_1usage(
		JNIEnv *env, jobject obj, jstring _pathArchive,
		jstring _pathToExtract) {
	const char *pathArchive = env->GetStringUTFChars(_pathArchive, 0);
	const char *pathToExtract = env->GetStringUTFChars(_pathToExtract, 0);

	test_args[2] = pathToExtract;
	test_args[3] = pathArchive;

	// process
	jint ret = andro7za_main(ARGC, test_args);

	// Release strings
    env->ReleaseStringUTFChars(_pathArchive, pathArchive);
    env->ReleaseStringUTFChars(_pathToExtract, pathToExtract);

	return ret;
}

/***************************************************************************/
int Main2(int numArgs, const char *args[]);
#ifdef EXE
int main(int argc, const char *argv[]){
    Main2(argc, argv);
}
#endif

int main2(const char *args){
    const char *argv[40]={"7za", NULL};
    char abuffer[1024]={0};
    int i, index=1;
    LOG_D("%s", args);
    if(args){
        argv[index++]=abuffer;
        for(i=0; i<sizeof(abuffer)-1; i++){
            char c=*args++;
            abuffer[i]=c;
            if(c==0){
                break;
            }else if(c==' '){
                abuffer[i]=0;
                argv[index++]=abuffer+i+1;
                if(index>=40) break;
            }
        }
    }
    LOG_D("%d, %s, %s", index, argv[1], argv[2]);
    return Main2(index, argv);
}

extern "C" JNIEXPORT jint JNICALL Java_com_snda_Andro7z_Andro7za_run
        (JNIEnv *env, jclass cls, jstring args_){
    const char *args = (*env).GetStringUTFChars( args_, 0);
    int i=main2(args);
    (*env).ReleaseStringUTFChars(args_, args);
    return i;
}
